package com.nd.mobile.study.common;

import android.content.Context;
import android.os.AsyncTask;

import com.nd.mobile.study.common.util.ExceptionHandler;
import com.nd.mobile.study.view.helper.ToastHelper;
import com.nd.mobile.study.view.widget.Loading;

public abstract class SimpleAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

	protected Context	mContext;
	private String		mErrorMsg;
	private Loading		mLoading;

	public SimpleAsyncTask(Context context) {
		super();
		mContext = context;
		mLoading = ((BaseActivity) mContext).getLoading();
	}

//	@Override
//	protected void onPreExecute() {
//		mLoading.p();
//	}

	@Override
	protected Result doInBackground(Params... params) {
		Result result = null;
		try {
			result = onLoad(params);
		} catch (Exception e) {
			e.printStackTrace();
			mErrorMsg = ExceptionHandler.parseExceptionInfo(e);
		}
		return result;
	}

	@Override
	protected void onPostExecute(Result result) {
		if (null != mErrorMsg) {
			onHandleError(mErrorMsg);
		} else {
			onUI(result);
		}
		mLoading.v();
	}

	protected abstract Result onLoad(Params... params) throws Exception;

	protected abstract void onUI(Result result);

	protected void onHandleError(String errorMsg) {
		ToastHelper.displayToast(mContext, errorMsg);
	}
}
